﻿using MQTT.Server.Controllers;
using MQTT.Server.ExtensionServer.MQTTClient;
using MQTT.Server.GlobalConfig;
using MQTTnet.Client;

namespace MQTT.Server.ExtensionServer
{
    public static class MqttClientServerExtension
    {
        public static IServiceCollection AddMqttClientHostedService(this IServiceCollection services, AppConfig appConfig)
        {
            services.AddMqttClientServiceWithConfig(builder =>
            {
                builder
                .WithCredentials(appConfig.UserName, appConfig.Password)
                .WithClientId(appConfig.ClientID)
                .WithWillQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.ExactlyOnce)
                .WithTcpServer("localhost", appConfig.TcpPort);
            });
            return services;
        }

        private static IServiceCollection AddMqttClientServiceWithConfig(this IServiceCollection services, Action<MqttClientOptionsBuilder> configure)
        {
            services.AddSingleton(serviceProvider =>
            {
                var optionBuilder = new MqttClientOptionsBuilder();
                configure(optionBuilder);
                return optionBuilder.Build();
            });
            services.AddSingleton<MqttClientController>();
            services.AddSingleton<IHostedService>(serviceProvider =>
            {
                return serviceProvider.GetService<MqttClientController>();
            });
            services.AddSingleton(serviceProvider =>
            {
                var mqttClientService = serviceProvider.GetService<MqttClientController>();
                var mqttClientServiceProvider = new MqttClientServiceProvider(mqttClientService);
                return mqttClientServiceProvider;
            });
            return services;
        }
    }
}
